<?php

namespace App\Models\Sys;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UserRole extends Model
{
    protected $table = 'sys_user_role';

    //获取用户所有的角色id
    public function getRoleByUserId($id)
    {
        return $this->where(['user_id'=>$id])->pluck('role_id');
    }


    //更新用户所属角色
    public function saveUserRole($id, array $roleId)
    {
        foreach ($roleId as $v) {
            $insertData[] = [
                'user_id' => $id,
                'role_id' => $v
            ];
        }
        DB::beginTransaction();
        try {
            DB::table('sys_user_role')->where('user_id', '=', $id)->delete();
            DB::table('sys_user_role')->insert($insertData);
            DB::commit();
            return true;
        } catch (Exception $e) {
            DB::rollBack();
            return false;
        }
    }
}
